package com.zxl.test.domain;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Random;
import java.util.Vector;

import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.zxl.test.Get51job;

public class SearchDomain {

	private static Get51job g51j = new Get51job();
	private static StringBuffer sb = new StringBuffer();
	private static String s = new String();
	private static String letter[] = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
	private static String number[] = {"0","1","2","3","4","5","6","7","8","9"};
	
	/**
	 * 传域名请求并返回数据
	 * @throws IOException
	 */
	public static void testPost(String domain) throws IOException {

		URL url = new URL("http://cnkuai.cn/searchdns.asp");
		
		URLConnection connection = url.openConnection();
		connection.setDoOutput(true);
		
		OutputStreamWriter out = new OutputStreamWriter(connection
				.getOutputStream(), "8859_1");
		out.write("Cp_DnsName=.com&User_DnsName=" + domain);
		
		out.flush();
		out.close();
		
		String sCurrentLine = "";
		StringBuffer sTotalString = new StringBuffer();
		InputStream l_urlStream = connection.getInputStream();
		
		BufferedReader l_reader = new BufferedReader(new InputStreamReader(l_urlStream));
		while ((sCurrentLine = l_reader.readLine()) != null) {
			sTotalString.append(sCurrentLine + "\r\n");

		}
//		System.out.println(sTotalString);
		parserHtml(sTotalString.toString());
	}
	
	/**
	 * 解析返回结果
	 * @param s
	 */
	public static void parserHtml(String s){
		sb.setLength(0);
		try {
			Parser p = new Parser(s);
//			TextExtractingVisitor visitor = new TextExtractingVisitor();
//			p.visitAllNodesWith(visitor);
//			System.out.println(visitor.getExtractedText());
			
			AndFilter filter = new AndFilter(new TagNameFilter("input"),
					new HasAttributeFilter("name", "domains"));

			NodeList nodes = p.parse(filter);
			for(int i = 0; i < nodes.size(); i++){
				TagNode node = (TagNode)nodes.elementAt(i);
				Vector v = node.getAttributesEx();
				if(v.get(8).toString().equals("disabled")) continue;
				s = v.get(6).toString().replace("value=", "").replace("\"", "");
//				System.out.println(v.get(6).toString().replace("value=", "").replace("\"", "") + "\t" + ((v.get(8).toString().equals("disabled"))?"NO":"YES"));
				sb.append(s + "\r\n");
				System.out.println(s);
//				System.out.println(node.toPlainTextString());
			}
			g51j.writeFile("D:\\domain.txt", sb);
			
		} catch (ParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 生成s个随机n位数
	 * @param n
	 * @param s
	 */
	public static void randomNumber(int n, int s){
		Random r = new Random();
		String s_max = "1";
		
		for(int j = 0; j < n; j++){
			s_max += "0";
		}
		
		String s_min = s_max.substring(0, s_max.length()-1);
		
		int n_max = Integer.parseInt(s_max);
		int n_min = Integer.parseInt(s_min);
		System.out.println(n_max);
		System.out.println(n_min);
		
		for(int i = 0; i < s; i++){
			try {
				testPost(r.nextInt(n_max-n_min+1)+n_min+"");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static void orderNumber(){
		for(int a = 0; a < number.length; a++){
			for(int b = 0; b < number.length; b++){
				for(int c = 0; c < number.length; c++){
					for(int d = 0; d < number.length; d++){
						System.out.println(number[a] + number[b] + number[c] + number[d]);
						for(int e = 0; e < number.length; e++){
							try {
								testPost(number[a] + number[b] + number[c] + number[d] + number[e]);
							} catch (IOException ex) {
								// TODO Auto-generated catch block
								ex.printStackTrace();
							}
						}
					}
				}
			}
		}
	}
	
	/**
	 * 生成s个随机n位字母
	 * @param n
	 * @param s
	 */
	public static void randomLetter(int n, int s){
		Random r = new Random();
		String s_temp  = "";
		int len = letter.length;
		
		for(int j = 0; j < s; j++){
			s_temp = "";
			for(int i = 0; i < n; i++){
				s_temp += letter[r.nextInt(len)];
			}
			
			try {
				testPost(s_temp);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
	/**
	 * 遍历四位字母的域名
	 */
	public static void orderLetter(){
		for(int a = 0; a < letter.length; a++){
			for(int b = 0; b < letter.length; b++){
				for(int c = 0; c < letter.length; c++){
					System.out.println(letter[a] + letter[b] + letter[c]);
					for(int d = 0; d < letter.length; d++){
						try {
							testPost(letter[a] + letter[b] + letter[c] + letter[d]);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
		}
	}
	
	/**
	 * 输入命令
	 * @return
	 */
	public static String inputCommand(){
		String command = "";
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		try {
			command = bf.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return command;
	}
	
	public static void main(String[] args) throws IOException {
		String cmd = "";
		String s[];
		
		while(true){
			System.out.println("------------------------");
			System.out.println("  1.查询一个域名；");
			System.out.println("  2.生成s次随机n位数的域名；");
			System.out.println("  3.遍历四位数字的域名（慎用）；");
			System.out.println("  4.生成s次随机n位字母的域名；");
			System.out.println("  5.遍历四位字母的域名（慎用）；");
			System.out.println("  6.退出；");
			System.out.println("  如果有未注册的域名，屏幕会显示，而且D:\\domain.txt里也有哦！");
			System.out.println("------------------------");
			System.out.println("请选择：");
			
			String command = inputCommand();
			Long st = System.currentTimeMillis();
			if(command != null && !command.equals("")){
				if(command.length() > 1){
					System.out.println("未识别，请重新输入！");
					continue;
				}
				
				int n = Integer.parseInt(command);
				switch(n){
				case 1:
					System.out.println("请输入要查询的域名：");
					cmd = inputCommand();
					testPost(cmd);
					break;
				case 2:
					System.out.println("请问你需要生成几次几位数的域名（几位 几次，用空格分隔）？");
					cmd = inputCommand();
					cmd = cmd.replaceAll(" +", " ");
					s = cmd.split(" ");
					randomNumber(Integer.parseInt(s[0]),Integer.parseInt(s[1]));
					break;
				case 3:
					orderNumber();
					break;
				case 4:
					System.out.println("请问你需要生成几次几位字母的域名（几位 几次，用空格分隔）？");
					cmd = inputCommand();
					cmd = cmd.replaceAll(" +", " ");
					s = cmd.split(" ");
					randomLetter(Integer.parseInt(s[0]),Integer.parseInt(s[1]));
					break;
				case 5:
					orderLetter();
					break;
				case 6:
					System.exit(0);
				default:
					System.out.println("未识别，请重新输入！");	
				}
			}else{
				System.out.println("不能为空！");
			}
			
			Long et = System.currentTimeMillis();
			Long l = et-st;
			if(l < 1000){
				System.out.println("耗时" + l + "毫秒");
			}else if(l < 60000){
				System.out.println("耗时" + l/1000 + "秒");
			}else{
				System.out.println("耗时" + l/60000 + "分钟");
			}
		
		}
	}

}